package com.apanal.qlife.sys.service.impl;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.apanal.qlife.common.constants.Constants;
import com.apanal.qlife.common.exception.BusinessException;
import com.apanal.qlife.common.util.HttpUtil;
import com.apanal.qlife.common.util.PropertieUtil;
import com.apanal.qlife.common.util.TextFomat;
import com.apanal.qlife.sys.model.Checkcode;
import com.apanal.qlife.sys.service.CheckcodeService;
import com.apanal.qlife.sys.service.SMSService;

/**
 * 短信服务层接口实现类
 * 
 * @author shuliangxing
 * 
 * @date 2015-1-14上午11:36:08
 */
@Service
public class SMSServiceImpl implements SMSService {

	private static final Logger logger = Logger.getLogger(SMSServiceImpl.class);

	@Autowired
	CheckcodeService checkcodeService;

	@Override
	public void sendSMS(String mobile, String content) {
		// 发送短信完整url
		String url = "";
		// url编码
		String character = PropertieUtil.getPropertie("URL_CHARACTER");
		// 发送短信参数未填充的url
		String textMsgUrl = PropertieUtil.getPropertie("TEXT_MESSAGE_URL");
		// 发送短信签名
		String qm = PropertieUtil.getPropertie("QM_QLIFE");

		// 发送短信超时时间,单位毫秒
		int urlTimeOut = Integer.valueOf(PropertieUtil
				.getPropertie("SMS_TIMEOUT"));

		try {
			qm = URLEncoder.encode(qm, character);
			content = URLEncoder.encode(content, character);
			url = MessageFormat.format(textMsgUrl, qm, mobile, content);
			HttpUtil.getUrl(url, character, urlTimeOut);

		} catch (IOException e) {
			logger.error("短信发送失败,url=" + url + ",character=" + character
					+ ",urlTimeOut=" + urlTimeOut, e);
			throw new BusinessException("验证码发送失败，请稍后重试");
		}
	}

	@Override
	public String addAndSendForgetPwdCode(String mobile) {
		String result = Constants.CHECKCODE_MSG;

		// 发送短信内容
		String content = PropertieUtil.getPropertie("FORGET_PWD_CONTENT");
		// 验证码有效时间
		int validTime = Integer.valueOf(PropertieUtil
				.getPropertie("FORGET_PWD_VALID_TIME"));
		// 6位验证码
		String code = TextFomat.getRandomStr(6);
		content = MessageFormat.format(content, code, validTime);
		result = MessageFormat.format(result, validTime);

		// 先插入验证码后发送信息
		Checkcode checkcode = new Checkcode();
		checkcode.setCodType(1);
		checkcode.setCodMobile(mobile);
		checkcode.setCodCode(code);
		checkcode.setCodSendTime(new Date());
		checkcode.setCodUsed(false);
		checkcodeService.insert(checkcode);

		// 发送短信
		sendSMS(mobile, content);

		return result;
	}

}
